<?php
/**
 * @author PhuTP <phutp@younetco.com>
 * @author HoangLM <hoanglm@younetco.com>
 * @author LocLX <loclx@younetco.com>
 * @package Contest
 * @version 3.0
 */


/**
 * Class for handle creating/edit contest
 */
class Contest_ManageController extends YouNet_Controller_Action {

	/**
	 *
	 * @var Core_Model_Contest
	 */
	private $_contest;
	private $_id;
	private $_id_page;
	private $_viewState = null;

	const PARAM_VIEW_STATE = Core_Util::VIEW_STATE_MANAGE;
	public function preDispatch() {
		parent::preDispatch();

		$this->view->use_admin_menu = 1;
		$this->view->i_count_step	= 0;

		$this->_id_page		= $this->_getParam('id_page');
		$this->_id			= $this->_getParam('id');
		$this->_viewState	= time();

		$action = $this->getRequest()->getActionName();

		$this->view->render('manage/select_fanpages.phtml');
		if( !empty($this->_id_page) && !in_array($this->_id_page, $this->_social->getUserPageIds()) )
		{
			$this->_social->redirect('/contest/manage/list');
		}
		//only some actions allows empty 'id'
		if(empty($this->_id))
		{
			if (!in_array($action, array('list', 'create-basic', 'do-create-basic')))
			{
				throw new Exception('Bad request', 404);
			}
		}
		//all other actions require a valid 'id'
		else
		{
			$this->_contest = $this->_getContestRow();
			if( !empty($this->_contest->id) && $this->_contest->hasAdminPermission($this->_id_user, $this->_social->getUserPageIds()))
			{
				$this->view->i_count_step			= $this->_contest->countFinishedSteps();
				$this->view->isFinishedCreateDetail = $this->_contest->isFinishedCreateDetail();
				$this->view->isFinishedTimeline		= $this->_contest->isFinishedTimeline();
				$this->view->isFinishedCreateEntry	= $this->_contest->isFinishedCreateEntry();
				$this->view->isFinishedSettingTheme = $this->_contest->isFinishedSettingTheme();
			}
			else
			{
				throw new Exception('Bad request', 404);
			}
			$this->view->is_show_next_steps_menu = 1;
		}
	}

	private function _generateForm()
	{
		$form	= $this->_getForm();
		if( !isset($_POST['form_submitted']) )
		{
			if( !empty($this->_contest->id) )
			{
				$form->fill($this->_contest);
			}
            else if(!empty ($this->_id_page))
            {
                $form->populate(array(
                    Contest_Form_Basic::FANPAGE_NAME => array($this->_id_page)
                ));
            }
		}
		$this->view->contest	= $this->_contest;
		$this->view->form		= $form;
		$this->render('form');
	}

	public function listAction()
	{
		$q				= $this->_getParam('q');
		$page			= $this->_getParam(PARAM_PAGE_NAME,1);
		$arrSort        = $this->_getParam(PARAM_SORT_DEFAULT,array());
		$arrSort		= array_merge($arrSort,array('q' => $q));
		$contestTable	= new Core_Model_DbTable_Contests();
		if( !empty($this->_id_page) )
		{
			$selection		= $contestTable->getSelectionContestsListIdPage($this->_id_page, $arrSort);
		}
		else
		{
			$selection		= $contestTable->getSelectionContestsListByAdmin($this->_id_user, $this->_social->getUserPageIds(), $arrSort);
		}
		$paginator      = Zend_Paginator::factory($selection);
		$paginator->setCurrentPageNumber($page);
		$paginator->setItemCountPerPage(LIST_ITEM_PER_PAGE);
		$this->view->paginator      = $paginator;
		$this->view->{self::PARAM_VIEW_STATE} = $this->_viewState;
	}
	public function thanksAction()
	{

	}
	/**
	 * @return Core_Model_Contest
	 */
	private function _getContestRow()
	{
		return Core_Model_DbTable_Contests::getContestRow($this->_getCurrentContestId());
	}

	public function createBasicAction()
	{
		if( $this->_contest instanceof Core_Model_Contest)
		{
			$this->_getForm()->setContest($this->_contest);
		}
		$this->_generateForm();
	}

	public function doCreateBasicAction()
	{
		if( isset($_POST['form_submitted']) )
		{
			$form = $this->_getForm();
			if( $form->isValid($_POST) )
			{
				$arrValues	= $form->getValidValues($_POST);				
				$contestRow = $this->_getContestRow();
				$contestRow->doSaveBasic($this->_id_user, $arrValues);				
				
				if( $contestRow->save() )
				{
                    $contestRow->updateFanpageProcess(
                        $arrValues[Contest_Form_Abstract::FANPAGE_NAME],
                        $this->_social->getPageList()
                    );
                    
                    $contestRow->initShareConfig(array(
                        'id_contest' => $contestRow->id,
                        'title' => $contestRow->title,
                        'description' => $contestRow->description
                    ));

                    $this->_redirect(
                        $this->view->url(array('action' => 'create-phase', 'id' => $contestRow->id , 'id_page' => $this->_id_page)) . '?' . $_SERVER['QUERY_STRING'], array(
                            'prependBase' => false
                        )
                    );
				}
			}
		}
        
		$form->setContest($this->_getContestRow());
		$this->_generateForm();
	}

	public function createEntryAction()
	{
        $this->_generateForm();
	}
    
    /**
     * This action use to create/edit list entry fields of a contest
     * to collect user information when they submit an entry.
     * There have some rules:
     * <ol>
     * <li>Username/(Firstname|Middlename|LastName) field only switched between both of them to display</li>     
     * </ol>
     * @version 3.0
     * @throws Zend_Exception
     * @throws Exception
     */
	public function doCreateEntryAction()
	{
		if( isset($_POST['form_submitted']) )
		{
			$form = $this->_getForm();
			
			if( $form->isValid($_POST) )
			{
				try
				{
					$this->_contest->getTable()->getAdapter()->beginTransaction();
					$iSeeker = 0;
					$arrValues			= $form->getValidValues($_POST);
                    $isUseFullname		= false;
                    $arrFieldTypes		= Core_Model_DbTable_EntryFields::getListFieldTypes();

                    $contestFieldTable	= new Core_Model_DbTable_EntryFields();
                    $arrContesFieldRows	= array();
                    $fullnameField		= $arrValues[Contest_Form_EntryField::HELPER_CODE_FIELD][Core_Model_DbTable_EntryFields::INDEX_FULL_NAME];
                    if( $fullnameField[Core_Model_DbTable_EntryFields::INDEX_FULL_NAME] == 1)
                    {
                        $isUseFullname		= true;
                    }
                    foreach($arrValues[Contest_Form_EntryField::HELPER_CODE_FIELD] as $type => $arrFieldValues)
                    {
                        //@Must to create an empty value
                        $contestFieldRow				= null;
                        //Ruturn current value of $arrFieldValues array
                        $is_used						= isset($arrFieldValues[$type])?$arrFieldValues[$type]:0;
                        $type				= (int)$type;
                        $idEntryField					= !empty($arrFieldValues[Contest_Form_EntryField::NAME_ID_ENTRY_FIELD])?$arrFieldValues[Contest_Form_EntryField::NAME_ID_ENTRY_FIELD]:0;
                        if( !empty($idEntryField) )
                        {
                            $contestFieldRow			= $contestFieldTable->findOne($idEntryField);
                            if( !empty($contestFieldRow->id)
                                && ($contestFieldRow->id_contest != $this->_contest->id))
                            {
                                throw new Exception('Access denied',302); 
                            }
                        }
                        else
                        {
                            $contestFieldRow			= $contestFieldTable->createRow();
                        }

                        $contestFieldRow->label					= $arrFieldTypes[$type]['label'];
                        $contestFieldRow->is_displayed          = $is_used;
                        if( isset($arrFieldValues[Contest_Form_EntryField::NAME_IS_REQUIRED]) )
                        {
                            $contestFieldRow->is_required		= $arrFieldValues[Contest_Form_EntryField::NAME_IS_REQUIRED];
                        }
                        else
                        {
                            $contestFieldRow->is_required		= $arrFieldTypes[$type]['is_required'];
                        }
                        $contestFieldRow->type					= $type;
                        $arrContesFieldRows[$iSeeker++]			= $contestFieldRow;
                    }

					if( isset($arrValues['term_and_condition']) )
					{
						$this->_contest->term_and_condition = $arrValues['term_and_condition'];
					}
					if( isset($arrValues['message_thanks']) )
					{
						$this->_contest->message_thanks		= $arrValues['message_thanks'];
					}
					if( isset($arrValues['is_using_captcha']) )
					{
						$this->_contest->is_using_captcha	= $arrValues['is_using_captcha'];
					}
					$this->_contest->setIsFinishedCreateEntry(true);
					if( $this->_contest->save() )
					{
						for($i = 0; $i < $iSeeker; $i++)
						{
                        	$arrContesFieldRows[$i]->is_entry		= 0;
							if( empty($arrContesFieldRows[$i]->id_contest) )
							{
								$arrContesFieldRows[$i]->id_contest		= $this->_contest->id;
							}
                            
                            if($arrContesFieldRows[$i]->type == Core_Model_DbTable_EntryFields::INDEX_FULL_NAME)
                            {
                                $arrContesFieldRows[$i]->is_displayed = 
                                        $isUseFullname?Core_Model_IEntryFields::STATUS_DISPLAYED:Core_Model_IEntryFields::STATUS_UNDISPLAYED;
                            }
                            else if(in_array($arrContesFieldRows[$i]->type, array(
                                        Core_Model_DbTable_EntryFields::INDEX_FIRST_NAME,
                                        Core_Model_DbTable_EntryFields::INDEX_MIDDLE_NAME,
                                        Core_Model_DbTable_EntryFields::INDEX_LAST_NAME ))
                            )
                            {
                                $arrContesFieldRows[$i]->is_displayed = 
                                        !$isUseFullname?Core_Model_IEntryFields::STATUS_DISPLAYED:Core_Model_IEntryFields::STATUS_UNDISPLAYED;
                            }
                            
							$arrContesFieldRows[$i]->save();
						}
                        
						$this->_contest->getTable()->getAdapter()->commit();
                        $this->_redirect(
                            $this->view->url(array('action' => 'setting-theme', 'id' => $this->_contest->id)) . '?' . $_SERVER['QUERY_STRING'], array(
                                'prependBase' => false
                            )
                        );
					}
				}
				catch(Zend_Exception $e)
				{
					$this->_contest->getTable()->getAdapter()->rollBack();
					throw $e;
				}
			}
		}
		$this->_generateForm();
	}

	public function settingThemeAction()
	{
		$this->_generateForm();
	}

	public function doSettingThemeAction()
	{
		if( isset($_POST['form_submitted']) )
		{
            $_POST['notify_email'] = iconv('', 'ASCII//TRANSLIT', $_POST['notify_email']);
			$_POST['notify_email'] = preg_replace('/\s+/', "", $_POST['notify_email']);
            
			$form			= $this->_getForm();
            
			/*@var $form Contest_Form_Theme*/
			if( $form->isValid($_POST) )
			{
				$contestRow = $this->_getContestRow();
				$arrValues	= $form->getValidValues($_POST);
                
                $contestRow->doSaveThemSetting($arrValues, $form);
				$contestRow->setIsFinishedSettingTheme(true);
				if( $contestRow->save() )
				{
                    $contestRow->updateShareConfig($arrValues, $form);
                    
					$redirect_url = $this->_getParam('redirect_url', $this->view->url(array('action' => 'list')));
					$this->_redirect($redirect_url, array(
						'prependBase' => false
					));
				}
			}
		}
		$this->_generateForm();
	}

	public function createPhaseAction()
	{
		$this->_generateForm();
	}

	public function doCreatePhaseAction()
	{
		if( isset($_POST['form_submitted']) )
		{
			if( !empty($this->_contest->id) )
			{
				$form				= $this->_getForm();
				$phaseTable			= new Core_Model_DbTable_Phases();
				$phaseList			= $this->_contest->getPhasesList();

				if( !$form->isValid($_POST,$this->_contest) )
				{
					$arrPhaseValues		= $_POST[Contest_Form_Advanced::SUBFORM_PHASE];
					$n = count($arrPhaseValues);
					for ($i = 0; $i < $n; $i++)
					{
                        $isLimittedEdit = false;
						$phaseRow	= null;
						if( !empty($phaseList) && $phaseList->current() )
						{
							$phaseRow				= $phaseList->current();
                            $isLimittedEdit         = $this->_contest->isLimittedEdit($phaseRow->date_start);
							$phaseList->next();
						}
						else
						{
                            $phaseRow				= $phaseTable->createRow();
						}
						if( isset($_POST['is_use_phase']) && isset($_POST['is_use_phase'][$i]) )
						{
							//FBCONTEST-873
							if( !isset($arrPhaseValues[$i]) )
							{
								break;
							}
							if( !($phaseRow instanceof Core_Model_Phase) )
							{
								throw new Exception('Access is denied',302);
							}							
							$subForm	= $form->getSubForm(Contest_Form_Advanced::SUBFORM_PHASE.$i);
							$arrValues	= $subForm->getValidValues($arrPhaseValues[$i],true);

							if( isset($arrValues['name']) )
							{
								$phaseRow->name			= $arrValues['name'];
							}
							if( isset($arrValues['description']) )
							{
								$phaseRow->description	= $arrValues['description'];
							}

							if( isset($arrValues['date_start']) )
							{
								$temp					= strtotime($arrValues['date_start']);
								$date_start				= mktime(0, 0, 1, date('m', $temp), date('d', $temp), date('Y', $temp));
								$phaseRow->date_start	= $date_start;
							}

							if( isset($arrValues['date_end']) )
							{
								$temp					= strtotime($arrValues['date_end']);
								$date_end				= mktime(23, 59, 59, date('m', $temp), date('d', $temp), date('Y', $temp));
								$phaseRow->date_end		= $date_end;
							}
							$phaseRow->id_contest	= $this->_contest->id;
							$arrOptions = Contest_Form_Advanced::GetOptionsArray();
							if( !empty($arrOptions) )
							{
								foreach($arrOptions as $opt)
								{
									$phaseRow->$opt = 0;
									if( !empty($arrValues['options']) )
									{
										if( in_array($opt,$arrValues['options']) )
										{
											$phaseRow->$opt = 1;
										}
									}
								}
							}
							$phaseRow->save();
						}
						else
						{
							if( !empty($phaseRow->id) )
							{
								if( !$isLimittedEdit )
								{
									$phaseRow->delete();
								}
								else
								{
									throw new Exception('Access is denied',302);
								}
							}
						}
					}
                    /*
                     * Code change time zone
                     */
                    $arrValues = $form->getValidValues($_POST);
                    $time_zone = isset($arrValues['time_zone'])?$arrValues['time_zone']:0;
                    if( $this->_contest->time_zone !== $time_zone )
                    {
                        $this->_contest->time_zone	= $time_zone;
                        $this->_contest->setIsFinishedTimeline(true);
                        $this->_contest->save();
                    }
				}
			}
			if( !$form->isErrors() )
			{
				//$this->_social->redirect('/contest/manage/create-entry/id/'.$this->_contest->id);
                $this->_redirect(
                    $this->view->url(array('action' => 'create-entry', 'id' => $this->_contest->id)) . '?' . $_SERVER['QUERY_STRING'], array(
                        'prependBase' => false
                    )
                );
			}
		}
		$this->_generateForm();
	}

	/**
	 *
	 * @staticvar null $form
	 * @return Contest_Form_Abstract
	 */
	private function _getForm()
	{
		static $form	= null;
		if( !($form instanceof YouNet_Form) )
		{
			$id				= $this->_getCurrentContestId();
			$appendParam	= '';
			if( $id > 0)
			{
				$appendParam = '/id/'.$id;
			}
			$moduleName			= $this->_getParam('module');
			$controllerName		= $this->_getParam('controller');
			$action				= $this->_getParam('action');
			$prefix				= '/'.$moduleName.'/'.$controllerName;
			$doAction			= '';
			switch($action)
			{
				case 'create-basic':
				case 'do-create-basic':
					$form		= new Contest_Form_Basic();
					$doAction	= 'do-create-basic';
					break;
				case 'create-entry':
				case 'do-create-entry':
					$form		= new Contest_Form_EntryField(array('contest' => $this->_getContestRow()));
					$form->setBackAction($this->_social->url($prefix),'create-phase',$id);
					$doAction	= 'do-create-entry';
					break;
				case 'setting-theme':
				case 'do-setting-theme':
					$form		= new Contest_Form_Theme(array('contest' => $this->_getContestRow()));
					$form->setBackAction($this->_social->url($prefix),'create-entry',$id);
					$doAction	= 'do-setting-theme';
					break;
				case 'create-phase':
				case 'do-create-phase':
					$form = new Contest_Form_Advanced(array('contest' => $this->_getContestRow()));
					$form->setBackAction($this->_social->url($prefix),'create-basic',$id);
					$doAction	= 'do-create-phase';
					break;
			}
			if( $this->_getContestRow()->isLimittedEdit() )
			{
				$form->disableFields();
			}
			$moduleName			= $this->_getParam('module');
			$controllerName		= $this->_getParam('controller');
			$form->setSubmitAction($this->view->baseUrl($prefix),$doAction,$id);
		}
		return $form;
	}

	private function _getCurrentContestId()
	{
		return $this->_getParam('id',0);
	}

	/**
	 *
	 * @param array $arrFanpageIds
	 */
	private function _updateFanpageProcess(array $arrFanpageIds,$id_contest = null)
	{
		$arrPages			= $this->_social->getPageList();
		$contestPageTable	= new Core_Model_DbTable_Pages();
		if( empty($id_contest) )
		{
			$id_contest			= $this->_getCurrentContestId();
		}
		Core_Model_DbTable_Contests::removePageCache($id_contest);
		foreach($arrPages as $id_page => $name_page)
		{
			$contestPageRow					= $contestPageTable->findOne($id_page, $id_contest);
			if( in_array($id_page, $arrFanpageIds) )
			{
				if( empty($contestPageRow) )
				{
					$contestPageRow				= $contestPageTable->createRow();
				}
				$contestPageRow->id_page	= $id_page;
				$contestPageRow->name_page	= $name_page;
				$contestPageRow->id_contest = $id_contest;
				$contestPageRow->save();
			}
			else
			{
				if( !empty($contestPageRow) )
				{
					$contestPageRow->delete();
				}
			}
		}
	}

	public function publishAction()
	{
		$error = array();
		if( !$this->_contest->isPublished() )
		{
			if( $this->_contest->canPublished($error) )
			{
				$this->_contest->status = Core_Model_Contest::STATUS_PUBLISHED;
				$this->_contest->save();
			}
			else
			{
				$strMessage = '<strong>'.YouNet_Util::translate('FAILED_TO_PUBLISH').':</strong>';
				if( !empty($error) )
				{
					$strMessage .= '<ul><li>'.implode('</li><li>',$error).'</li></ul>';
				}
				Core_Util::setLatestMessage($strMessage,'manage_publish');
			}
		}
		$this->_redirectBack();
	}

	public function hideAction()
	{
		if ($this->_contest->status != Core_Model_Contest::STATUS_HIDDEN)
		{
			$this->_contest->status = Core_Model_Contest::STATUS_HIDDEN;
			$this->_contest->save();
		}
		$this->_redirectBack();
	}

	private function _redirectBack()
	{
		$this->disableAutoRender();
		$session		= $this->_getSession();
		$view_state		= 0;
		if( !empty($_COOKIE[self::PARAM_VIEW_STATE]) )
		{
			$view_state = $_COOKIE[self::PARAM_VIEW_STATE];
		}
		$arrUrl			= $session->url;
		$url			= '';
		if( !empty($arrUrl) && isset($arrUrl[$view_state]) )
		{
			$url		= $arrUrl[$view_state];
		}
		//Try to avoid loop
		if( !empty($url) && $url != $this->_getCurrentUri() )
		{
            $this->_redirect($this->view->baseUrl($url),
                            array('prependBase' => false)
                );
                   
		} 
         
		else
		{
            $this->_redirect($this->view->baseUrl('/contest/manage/list'),
                            array('prependBase' => false)
                );
            
		}
	}

	public function postDispatch() {
		$url			= $this->_getCurrentUri();
		$session		= $this->_getSession();
		$arrUrl			= $session->url;
		if( empty($arrUrl) || !is_array($arrUrl) )
		{
			$arrUrl = array();
		}

		$arrUrl[$this->_viewState] = $url;
		//Limit 10
		foreach($arrUrl as $key => $value)
		{
			if( count($arrUrl) >= 10)
			{
				unset($arrUrl[$key]);
			}
		}
		$session->url	= $arrUrl;
	}

	private function _getCurrentUri()
	{
		$uri			= $_SERVER['REQUEST_URI'];
		$uri			= substr($uri,strlen($this->view->baseUrl('/')) - 1);
		return $uri;
	}
	/**
	 *
	 * @return \Zend_Session_Namespace
	 */
	private function _getSession()
	{
		$session = Zend_Registry::get('session');
		return $session;
	}
    
    public function downloadskinAction()
	{
        $this->disableAutoRender();
		if (!empty($this->_contest->skin))
		{
			$file = $this->_contest->getSkinPath();
			header("Pragma: public", true);
			header("Expires: 0"); // set expiration time
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Content-Type: application/force-download");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header("Content-Disposition: attachment; filename=".basename($file));
			header("Content-Transfer-Encoding: binary");
			echo file_get_contents($file);
		}		
	}
    public function downloadskindefaultAction()
	{
        $this->disableAutoRender();
        $file = STATIC_PATH.'/media/skin/classic/fanpage.css';
        header("Pragma: public", true);
        header("Expires: 0"); // set expiration time
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Disposition: attachment; filename=".basename($file));
        header("Content-Transfer-Encoding: binary");
        echo file_get_contents($file);
				
	}
}
